<?php
class mcz_Role extends mcz_Object
{
	protected $fields = array(
		'id' => array('cast' => 'integer'),
		'label' => array('cast' => 'string',
						 'unique' => true,
						 'notblank' => true)
	);

	public function addPermissions(array $labels)
	{
		foreach($labels as $label)
		{
			$this->addPermission($label);
		}
	}

	public function addPermission($label)
	{
		if(empty($this->id))
		{
			$this->save();
		}
		$perm = mcz_Permission::store($label);
		mcz_RolePermission::clean($perm->id, $this->id);
		$rp = new mcz_RolePermission();
		$rp->role_id = $this->id;
		$rp->permission_id = $perm->id;
		$rp->save();
	}

	public function removePermission($label)
	{
		$perm = mcz_Permission::store($label);
		self::dbh()->exec('delete from mcz_RolePermission where permission_id = ?', array($perm->id));
	}

	public static function store($label, array $permissions = null)
	{
		$res = self::hydrate(get_class(),
							 self::dbh()->fetch('* from ' . get_class() .
												' where label = ?', array($label)));
		if($res)
		{
			return $res[0];
		}
		$res = new mcz_Role();
		$res->label = $label;
		$res->save();
		$res->addPermissions($permissions);
		return $res;
	}
}